//
//  AppThemeManager.swift
//  app
//
//  Created by gy on 2023/7/18.
//

import Foundation
import AudioToolbox

/// 获取屏幕宽
var screenWidth : CGFloat {
    return UIScreen.main.bounds.width
}
var screenFixationWidth : CGFloat {
    return min(430, UIScreen.main.bounds.width)
}

/// 获取屏幕高
var screenHeight : CGFloat {
    return UIScreen.main.bounds.height
}

/// 底部导航栏高度
let kTabbarHeight = IsHaveHair ? 83 : 49

let kAppThemeManager = AppThemeManager.shared
class AppThemeManager {
    
    static let shared = AppThemeManager()
    
    private(set) var tabBarController: BaseTabBarController?
    /// 一键置灰 开关
    var isGreyOut: Bool = false {
        didSet {
            if isGreyOut {
                // 置灰
                setGreyOut()
            } else {
                // 清除
                clearGreyOut()
            }
        }
    }
    /// 按钮音效
    var isOpenTabVoice = true { // 下拉刷新和切换底部tabbar
        didSet {
            saveLocalSoundStatus()
        }
    }
    /// 是否开启长辈模式
    private(set) var fontScale: CGFloat = 1
    var isOpenElder = false {
        didSet {
            saveLocalElderMode()
            fontScale = isOpenElder == true ? 1.2:1
        }
    }
    
    init() {
        
    }
    
    /// 配置全局样式
    func configGlobalAppearances() {
        
        // tabbar
        configTabbarAppearamce()
        // naviBar
        configNavigationAppearamce()
        
        // 全局修改 TextField 光标颜色
        UITextField.appearance().tintColor = .app_themeColor
        
        // 加载缓存音效开关
        readLocalSoundStatus()
        // 加载缓存长辈模式
        readLocalElderMode()
        
    }
    
    /// 当前window
    static func keyWindow() -> UIWindow? {
        if #available(iOS 15.0, *) {
            let keyWindow = UIApplication.shared.connectedScenes
                .map({ $0 as? UIWindowScene })
                .compactMap({ $0 })
                .first?.windows.first
            return keyWindow
        }else {
            let keyWindow = UIApplication.shared.windows.first
            return keyWindow
        }
    }
    
}

// MARK: - TabBar
extension AppThemeManager {
    
    /// 加载窗口内容
    func generateWindowRootViewController() -> BaseTabBarController {
        
        let tabbarVC = BaseTabBarController()
        
        // 首页初始化
        let homeVC = HomeVC()
        homeVC.hidesBottomBarWhenPushed = false
        let homeNC = BaseNavigationController(rootViewController: homeVC)
        homeNC.tabBarItem = UITabBarItem(title: "首页", image: UIImage(named: "tabbar_home_unselect"), selectedImage: UIImage(named: "tabbar_home_select")?.withRenderingMode(.alwaysOriginal))
        
        // 收益初始化
        let earningsVC = EarningsVC()
        earningsVC.hidesBottomBarWhenPushed = false
        let earningsNC = BaseNavigationController(rootViewController: earningsVC)
        earningsNC.tabBarItem = UITabBarItem(title: "收益", image: UIImage(named: "tabbar_earnings_unselect"), selectedImage: UIImage(named: "tabbar_earnings_select")?.withRenderingMode(.alwaysOriginal))
        
        
        // 我的初始化
        let mineVC = MineVC()
        mineVC.hidesBottomBarWhenPushed = false
        let mineNC = BaseNavigationController(rootViewController: mineVC)
        mineNC.tabBarItem = UITabBarItem(title: "我的", image: UIImage(named: "tabbar_mine_unselect"), selectedImage: UIImage(named: "tabbar_mine_select")?.withRenderingMode(.alwaysOriginal))
        
        tabbarVC.viewControllers = [homeNC, earningsNC, mineNC]
        
        tabBarController = tabbarVC
        tabBarController?.selectedIndex = 0
        
        return tabbarVC
    }
    
    /// 配置 tabbar 样式
    private func configTabbarAppearamce() {
        
        guard let tabBarController = tabBarController else { return }
        
        // 设置背景
        if #available(iOS 15.0, *) {
            
            // 设置纯色
//            let appearance = UITabBarAppearance()
//            appearance.configureWithOpaqueBackground()
//            appearance.backgroundColor = .white
//            // 取消tabbar的毛玻璃效果
//            appearance.backgroundEffect = nil
//            tabBarController.tabBar.standardAppearance = appearance
//            tabBarController.tabBar.scrollEdgeAppearance = tabBarController.tabBar.standardAppearance
            
        }
        
    }
    
}

// MARK: - NavigationBar
extension AppThemeManager {
    
    /// 配置导航
    func configNavigationAppearamce() {
        let backImage = UIImage(named: "back_pop_black")
        let navBarAppearance = UINavigationBar.appearance(whenContainedInInstancesOf: [UINavigationController.self])
        navBarAppearance.backgroundColor = UIColor.white
        navBarAppearance.isTranslucent = false

        navBarAppearance.shadowImage = UIImage()
        if backImage != nil{
            navBarAppearance.backIndicatorImage = backImage?.withRenderingMode(.alwaysOriginal)
            navBarAppearance.backIndicatorTransitionMaskImage = navBarAppearance.backIndicatorImage
        }
        if #available(iOS 13.0, *) {
            let navigationBarAppearance = UINavigationBarAppearance.init()
            navigationBarAppearance.configureWithOpaqueBackground()
            navigationBarAppearance.backgroundColor = UIColor.white //设置导航栏背景色
            navigationBarAppearance.backgroundImage = UINavigationController().navigationBar.backgroundImage(for: .default)
            navigationBarAppearance.shadowImage = UIImage()
            navigationBarAppearance.shadowColor = UIColor.app_clear //去除导航栏阴影
            navigationBarAppearance.titleTextAttributes = [.font: UIFont.app_navBarTitleFont,
                                                           .foregroundColor : UIColor.black]
            
            let navigation = UINavigationController.init()
            navigation.navigationBar.scrollEdgeAppearance = navigationBarAppearance //带scroll滑动页面
            navigation.navigationBar.standardAppearance = navigationBarAppearance//常规页面
            UINavigationBar.appearance().standardAppearance = navigationBarAppearance
            UINavigationBar.appearance().scrollEdgeAppearance = UINavigationBar.appearance().standardAppearance//重新赋值
        }
        let barButtonItemAppearance = UIBarButtonItem.appearance(whenContainedInInstancesOf: [UINavigationController.self])
        barButtonItemAppearance.tintColor = .red
        barButtonItemAppearance.setBackButtonTitlePositionAdjustment(UIOffset(horizontal: -500, vertical: 0), for: .default)
        
    }
    func transparencyNavBar() {
        
        let navBarAppearance = UINavigationBar.appearance(whenContainedInInstancesOf: [UINavigationController.self])
        navBarAppearance.backgroundColor = UIColor.clear
        navBarAppearance.isTranslucent = true
        navBarAppearance.titleTextAttributes = [.foregroundColor: UIColor.white]

        let appearance = UINavigationBarAppearance()
        appearance.configureWithOpaqueBackground()
        appearance.backgroundColor = .clear
        appearance.shadowColor = .clear
        appearance.titleTextAttributes = [.font: UIFont.app_navBarTitleFont, .foregroundColor : UIColor.white]
        UINavigationBar.appearance().standardAppearance = appearance
        UINavigationBar.appearance().scrollEdgeAppearance = appearance
        
    }
    func unTransparencyNavBar() {
        
        let navBarAppearance = UINavigationBar.appearance(whenContainedInInstancesOf: [UINavigationController.self])
        navBarAppearance.backgroundColor = UIColor.white
        navBarAppearance.isTranslucent = false
        navBarAppearance.titleTextAttributes = [.foregroundColor: UIColor.black]
        
        let appearance = UINavigationBarAppearance()
        appearance.configureWithOpaqueBackground()
        appearance.backgroundColor = .white
        appearance.shadowColor = .clear
        appearance.titleTextAttributes = [.font: UIFont.app_navBarTitleFont, .foregroundColor : UIColor.black]
        UINavigationBar.appearance().standardAppearance = appearance
        UINavigationBar.appearance().scrollEdgeAppearance = appearance
        
    }
    
}

// MARK: - 全局高度
extension CGFloat {
    
    // -- btn
    static let app_btnHeight = 44.0
    static let app_btnCornerRadius = 6.0
    static let app_btnHorizontalPading = 44
    
    // -- line
    static let app_lineHieght = 1/UIScreen.main.scale
    
    // -- Alert
    static let app_alertShowInterval = 0.35
    static let app_alertHidenInterval = 0.35
    static var app_hubInterval = 1.5     // toast提示间隔
    
    // -- 手机号输入框高度
    static let app_phoneInputHeight = 57.0
    
}

// MARK: - 全局字体
extension UIFont {
    static let app_navBarTitleFont = kSetPingFangMedium(18)
    static let app_navBarItemTitleFont = kSetPingFangRegular(17)
}

// MARK: - 全局字体
extension UIColor {
    
    // --- 系统色
    /// 系统 黑
    static let app_black: UIColor = { .black }()
    /// 系统 红
    static let app_red: UIColor = { .red }()
    /// 系统 文字 红
    static let app_textRedColor: UIColor = { .red }()
    /// 系统黄
    static let app_yellow: UIColor = { .yellow }()
    /// 系统 文字 黄
    static let app_textYellowColor: UIColor = { #colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1) }()
    /// 系统 灰
    static let app_gray: UIColor = { .gray }()
    /// 系统 浅灰
    static let app_lightGray: UIColor = { .lightGray }()
    /// 系统 深灰
    static let app_darkGray: UIColor = { .darkGray }()
    /// 系统 蓝
    static let app_blue: UIColor = { .blue }()
    /// 卡片 蓝
    static let app_cardBlue: UIColor = { UIColor.init(hex: 0x3697FF) }()
    /// 卡片 红
    static let app_cardRed: UIColor = { kSetRGBA(r: 229.0, g: 58.0, b: 56.0, a: 1.0) }()
    /// 系统 绿
    static let app_green: UIColor = { .green }()
    /// 系统 文字 绿
    static let app_textGreenColor: UIColor = { kSetRGB(r: 112, g: 180, b: 98) }()
    /// 系统 白
    static let app_white: UIColor = { .white }()
    /// 系统 透明
    static let app_clear: UIColor = { .clear }()
    /// 系统 金
    static let app_golden: UIColor = { UIColor(hex: 0x64472B, alpha: 1) }()
    /// 系统 浅金
    static let app_lightGolden: UIColor = { UIColor(hex: 0xAC9557, alpha: 1) }()
    /// 按钮 黄色
    static let app_btnYellow: UIColor = { #colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1) }()
    /// 按钮 橘色
    static let app_btnOrange: UIColor = { #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1) }()
    /// 系统 head 背景粉色
    static let app_headPinkBackgroundColor: UIColor = { kSetRGB(r: 201, g: 49, b: 127) }()
    /// 1px 线灰
    static let app_lineColor: UIColor = {
        kSetRGBA(r: 228.0, g: 228.0, b: 228.0, a: 1.0)
    }()
    static let app_lineDarkColor: UIColor = {
        UIColor(red: 0.851, green: 0.851, blue: 0.851, alpha: 1)
    }()
    static var app_randomColor: UIColor {
        kSetRGB(r: CGFloat(arc4random()%255), g: CGFloat(arc4random()%255), b: CGFloat(arc4random()%255))
    }
    
    /// 主题色
    static let app_themeColor: UIColor = {
        UIColor(red: 0.98, green: 0.6, blue: 0.24, alpha: 1)
    }()
    static let app_themeStartColor: UIColor = {
        UIColor(red: 0.95, green: 0.684, blue: 0.439, alpha: 1)
    }()
    static let app_themeEndColor: UIColor = {
        UIColor(red: 0.983, green: 0.587, blue: 0.221, alpha: 1)
    }()
    static let app_themeGradientColors = [UIColor.app_themeStartColor.cgColor, UIColor.app_themeEndColor.cgColor]
    
    // --- UIView
    /// 页面背景颜色
    static let app_viewBackgroundColor: UIColor = {
        UIColor(red: 0.98, green: 0.98, blue: 0.98, alpha: 1)
    }()
    static let app_inputViewBackColor: UIColor = {
        UIColor(red: 0.973, green: 0.973, blue: 0.973, alpha: 1)
    }()
    
    // --- navbar
    /// 导航title 文字 颜色
    static let app_navbarTitleColor: UIColor = { .black }()
    /// 导航title 背景色 颜色
    static let app_navbarBackgroundColor: UIColor = { .white }()
    
    // --- tabbar
    /// 底部导航 选中 颜色
    static let app_tabbarSelectColor: UIColor = {
        app_themeColor
    }()
    /// 底部导航 未选中 颜色
    static let app_tabbarUnSelectColor: UIColor = {
        app_lightGray
    }()
    
    // --- 文字
    /// 文字黑色
    static let app_textBlackColor: UIColor = {
        UIColor(hex: 0x666666)
    }()
    /// 状态 文字 橘色
    static let app_textOrange: UIColor = { UIColor(red: 0.98, green: 0.6, blue: 0.24, alpha: 1) }()
    /// 文字 蓝色
    static let app_textLightBlueColor: UIColor = { UIColor(hex: 0x6EA8C1) }()
    /// 文字灰色
    static let app_textGrayColor: UIColor = {
        UIColor(red: 0.145, green: 0.165, blue: 0.208, alpha: 0.3) // 0xaeaeae
    }()
    /// 文字深灰色
    static let app_textDarkGrayColor: UIColor = {
        UIColor(hex: 0x252A35)
    }()
    /// 提示 文字 颜色
    static let app_promptTextColor: UIColor = {
        UIColor(hex: 0x9a9a9a)
    }()
    /// 价格文字颜色
    static let app_priceTextColor: UIColor = {
        UIColor.hex(hexString: "#EF4813")
    }()
    /// 文字详情颜色
    static let app_detaisltextColor: UIColor = {
        UIColor.hex(hexString: "#AFB9C0")
    }()
    
    // --- 按钮
    /// 按钮 未选中 颜色
    static let app_btnDisableBackColor: UIColor = {
        UIColor(red: 0.896, green: 0.896, blue: 0.896, alpha: 1)
    }()
    /// 按钮 选中 颜色
    static let app_btnNormalBackColor: UIColor = {
        app_themeColor
    }()
    /// 按钮 未选中 颜色
    static let app_btnDisableColor: UIColor = {
        .app_white
    }()
    /// 按钮 选中 颜色
    static let app_btnNormalColor: UIColor = {
        .app_white
    }()
    /// 微信背景色
    static let app_btnWechatColor: UIColor = {
        kSetRGBA(r: 31.0, g: 185.0, b: 34.0, a: 1.0)
    }()

    // --- Alert
    static let app_customAlertBackgroundColor: UIColor = {
        app_black.withAlphaComponent(0.5)
    }()
    static let app_customAlertLightBackgroundColor: UIColor = {
        app_black.withAlphaComponent(0.15)
    }()
}

// MARK: - 音效
extension AppThemeManager {
    
    /// 播放音效
    func playSystemSound(forResource: String) {
        
        guard isOpenTabVoice == true else { return }
        
        var soundID1 = SystemSoundID(0)
        if let url = Bundle.main.url(forResource: forResource, withExtension: nil) {
            AudioServicesCreateSystemSoundID(url as CFURL, &soundID1)
            AudioServicesPlaySystemSound(soundID1)
        }
    }
    /// 读取本地音效设置
    func readLocalSoundStatus() {
        isOpenTabVoice = UserDefaults.standard.bool(forKey: "GlobalSoundEffectSwitch")
    }
    /// 缓存本地音效
    func saveLocalSoundStatus() {
        UserDefaults.standard.setValue(isOpenTabVoice, forKey: "GlobalSoundEffectSwitch")
    }
}

// MARK: - 长辈模式
extension AppThemeManager {
    
    /// 读取本地音效设置
    func readLocalElderMode() {
        isOpenElder = UserDefaults.standard.bool(forKey: "GlobalElderMode")
    }
    /// 缓存本地音效
    func saveLocalElderMode() {
        UserDefaults.standard.setValue(isOpenElder, forKey: "GlobalElderMode")
    }
    
}

// MARK: - 一键置灰
extension AppThemeManager {
    
    /// 置灰
    private func setGreyOut() {
        guard let window = AppThemeManager.keyWindow() else { return }
        
        let overlay = UIViewOverLay(frame: window.bounds)
        overlay.translatesAutoresizingMaskIntoConstraints = false
        overlay.backgroundColor = .lightGray
        overlay.layer.compositingFilter = "saturationBlendMode"
        overlay.layer.zPosition = .greatestFiniteMagnitude
        window.addSubview(overlay)
    }
    /// 清除
    private func clearGreyOut() {
        guard let window = AppThemeManager.keyWindow() else { return }
        _ = window.subviews.map { subView in
            if subView is UIViewOverLay {
                subView.removeFromSuperview()
            }
        }
    }
    
}
class UIViewOverLay: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder) has not been implemented")
    }
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        return nil
    }

}

